import loginBg from "@/assets/image/login_bg.png";
import logoImg from "@/assets/image/logo_img.png";
import { getAddress, getUserInfo, getUserDetails } from "@/api/user";
import { mapMutations } from "vuex";
export default {
  components: {},
  data() {
    return {
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      markCodeStr: "",
      loginBg,
      logoImg
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    //code是登录所需最终参数
    const { authCode } = this.$route.query;

    if (authCode) {
      //登录接口
      this.handleLogin(authCode);
    } else {
      // this.getAccredit()
    }
  },
  methods: {
    toMourefun(){
      window.open("https://www.morefun.me/", "_blank");
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },

    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },

    handleLogin(code) {
      try {
        this.loading = true;
        this.$store
          .dispatch("user/login", { authCode: code })
          .then((res) => {
            this.getUserDetails();
            this.loading = false;
          })
          .catch(() => {
            this.$router.push({
              path: "/autherr",
            });
            this.loading = false;
          });
      } catch (error) {
        this.loading = false;
      }
    },

    // 授权地址
    async getAccredit() {
      await getAddress({state: "morefunoa"}).then((res) => {
        window.location.replace(res.data);
      });
    },

    // 获取用户详情
    async getUserDetails() {
      await getUserDetails().then((res) => {
        this.$router.push({
          path: "/",
        });
      }).catch(err=>{
        this.$router.push({
          path: "/autherr",
        });
      });
    },
  },
};